<?php if( ! defined('BASEPATH')) exit('No direct script access allowed');

class MY_Model extends CI_Model {
	
	public $count;
	protected $tbl;
	function __construct(){
		parent::__construct();
		
		//鍙栧緱鎵�湁琛�
    	$this->tbl = (object)config_item('table');
    	
	}
	
	function show_tables(){
	    $arr_table = array();
	    $rs = $this->db->query('show tables');
	    foreach ($rs->result() as $r){
	        $arr_table[] = $r->Tables_in_ed;
	    }
	    return $arr_table;
	}
	
	function save($tbl,$data){

		$this->deal_data($tbl,$data);

		$data = is_object($data) ? (array)$data : $data;
		
		unset($data['atime']);
		unset($data['utime']);
		
		//杩囨护闈炶〃灞炴�
		$query = $this->db->query("desc ".$tbl);
		$arr_all_field = array();//鎵�湁灞炴�
		$arr_key_field = array();//涓婚敭灞炴�
		foreach ($query->result() as $r){
			$arr_all_field[] = $r->Field;
			if($r->Key == 'PRI'){
				$arr_key_field[] = $r->Field;
			}
		}

		$arr_field = array();//鎵�敤灞炴�
		$arr_value = array();//鎵�敤鍊�
		foreach ($data as $k=>$v) {
			if(in_array($k, $arr_all_field)){
				$arr_field[] = "`".$k."`";
				$arr_value[] = $this->db->escape($v);
			}
		}
		
		//鏄彃浠惰繕鏄洿鏂�
		$update_flag = false;
		if(count($arr_key_field)>0){
			foreach ($data as $k=>$v) {
				if(in_array($k, $arr_key_field) && !empty($v)){
					$update_flag = true;
					break;
				}
			}
		}else{
			$update_flag = false;
		}

		if(!$update_flag){
			
			if(in_array('atime', $arr_all_field)){
				$arr_field[] = '`atime`';
				$arr_value[] = time();
			}
			
			if(in_array('utime', $arr_all_field)){
				$arr_field[] = '`utime`';
				$arr_value[] = time();
			}
			
			$sql = "insert into `".$tbl."` (
				".implode($arr_field, ',')."
			) values (
				".implode($arr_value, ',')."	
			)";
			
		}else{
			
			if(in_array('utime', $arr_all_field)){
				$arr_field[] = '`utime`';
				$arr_value[] = time();
			}
			
			$arr_set = array();
			foreach ($arr_field as $k=>$v){
				$arr_set[] = $v."=".$arr_value[$k];
			}
			
			$arr_where = array();
			foreach ($arr_key_field as $v){
				$arr_where[] = "`".$v."`=".$this->db->escape($data[$v]);
			}
			$sql = "update `".$tbl."` set ".implode($arr_set, ',')." 
				where ".implode($arr_where, ' and ');

		}
		
		if($this->db->query($sql)){
			if(!$update_flag){
				return $this->db->insert_id();
			}else{
				return $data['id'];
			}		
		}
		
		return 0;
		
	}
	
	function in($tbl,$cond){
		$this->db->from($tbl);
		$this->db->where($cond);
		$count = $this->db->count_all_results();
		if($count>0) return true;
		return false;
	}
	
	function row($tbl,$cond=array(),$rt = 'o'){
		$this->db->from($tbl);
		$this->db->where($cond);
		$query = $this->db->get();

		if($rt == 'o'){
			$list = $query->result();
		}else{
			$list = $query->result_array();
		}

		if(!empty($list)) return $list[0];

		return array();
	}
	
	function get_by_id($tbl,$id,$rt = 'o'){
		$this->db->from($tbl);
		$this->db->where(array('id'=>$id));
		$query = $this->db->get();
		if($rt == 'o'){
			$list = $query->result();
		}else{
			$list = $query->result_array();
		}
		if(!empty($list)) return $list[0];
		return array();
	}
	
	function insert($tbl,$data){
		//杩囨护闈炶〃灞炴�
		$query = $this->db->query("desc ".$tbl);
		$arr_all_field = array();//鎵�湁灞炴�
		foreach ($query->result() as $r){
			$arr_all_field[] = $r->Field;
		}
		$arr_field = array();//鎵�敤灞炴�
		$arr_value = array();//鎵�敤鍊�
		foreach ($data as $k=>$v) {
			if(in_array($k, $arr_all_field)){
				$arr_field[] = "`".$k."`";
				$arr_value[] = $this->db->escape($v);
			}
		}
		if(in_array('atime', $arr_all_field)){
			$arr_field[] = '`atime`';
			$arr_value[] = time();
		}
		
		if(in_array('utime', $arr_all_field)){
			$arr_field[] = '`utime`';
			$arr_value[] = time();
		}
		
		$sql = "insert into `".$tbl."` (
			".implode($arr_field, ',')."
		) values (
			".implode($arr_value, ',')."
		)";
		
		
		$this->db->query($sql); 
		
		return true;
		
	}
	
	function delete($tbl,$cond){
		return $this->db->delete($tbl,$cond);
	}
	
	function update($tbl,$data,$cond=array()){
		return $this->db->where($cond)->update($tbl,$data);
	}
	
	function count($tbl,$cond){

		$this->db->from($tbl);

		foreach ($cond as $k => $v) {
			if(is_array($v)){
				$this->db->where_in($k,$v);
			}else{
				if($filter_type = strstr($k,'|')){
					$t = explode('|', $k);
					$k = $t[0];
					$filter_type = trim($filter_type,'|');
					if($filter_type == 'l'){
						$this->db->like($k,$v);
					}elseif($filter_type == 'lb'){
						$this->db->like($k,'%'.$v);
					}elseif($filter_type == 'la'){
						$this->db->like($k,$v.'%');
					}
				}else{
					$this->db->where($k,$v);
				}

			}
		}

		return $this->db->count_all_results();
	}
	
	function get_all($tbl,$cond = array(),$ord='',$rownum = 0,$rt = 'o'){
		$this->db->from($tbl)->where($cond);
		if($rownum>0){
			$this->db->limit($rownum,0);
		}
		if(!empty($ord)){
			$this->db->order_by($ord);
		}
		$query = $this->db->get();
		if($rt == 'o'){
			return $query->result();
		}else{
			return $query->result_array();
		}
	}

    
	function get_kv($k){
		$r = $this->row($this->tbl->kvstore,array(),'a');
		$c = unserialize($r['kv']);
		if(!empty($c[$k])) return $c[$k];
		return null;
	}

	function set_kv($k,$v){
		$r = $this->row($this->tbl->kvstore,array(),'a');
		if(!empty($r['kv'])){
			$c = unserialize($r['kv']);
		}else{
			$c = array();
		}

		$c[$k] = $v;

		$c = serialize($c);

		if(!empty($r['kv'])){
			$this->update($this->tbl->kvstore,array('kv'=>$c));
		}else{
			$this->insert($this->tbl->kvstore,array('kv'=>$c));
		}

	}

	function del_kv($k){
		$r = $this->row($this->tbl->kvstore,array(),'a');
		if(!empty($r['kv'])){
			$c = unserialize($r['kv']);
			unset($c[$k]);
			$c = serialize($c);

			$this->update($this->tbl->kvstore,array('kv'=>$c));
			
		}
		return;

	}

	protected function deal_data($tbl,&$data){
    	
    	$t = explode('_', $tbl);

    	if($t[0].'_' != CUSTOM_TBL_PREFIX) return;
    	
    	$r_model = $this->row($this->tbl->model,array('mark'=>$t[1]),'a');
    	$attr = unserialize($r_model['attr']);

    	foreach ($attr as $k => $v) {
    		$attr[$v['name']] = $v;
    		unset($attr[$k]);
    	}

    	foreach ($data as $k => $v) {
    		
    		if(empty($attr[$k])) continue;

			if($attr[$k]['type'] == 'image'){
				$data[$k] = intval($v);
			}elseif($attr[$k]['type'] == 'images'){
				$data[$k] = trim($v,',');
			}

    	}
	}

	function get_page($tbl,$col='*',$cond = array(),$link=array(),$from = 0,$pagesize = 10,$ord='',$rt = 'o'){
		$this->count = $this->count($tbl,$cond);
		return mlist($tbl,$col,$cond,$link,$from,$pagesize,$ord,$rt);		
	}
	
	function show_col_models($tbl){
		$query = $this->db->query("desc ".$tbl);
		$arr_all_field = array();
		foreach ($query->result_array() as $r){
			$arr_all_field[] = $r;
		}
		
		return $arr_all_field;
	}
	
	function get_cols($tbl){
		$query = $this->db->query("desc ".$tbl);
		$arr_all_field = array();
		foreach ($query->result() as $r){
			$arr_all_field[] = $r->Field;
		}
		
		return $arr_all_field;
	}
	
	public function query($sql){
	    return $this->db->query($sql);
	}
	
}

